package com.zero.yygh.msm.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.zero.yygh.msm.service.MsmService;
import com.zero.yygh.msm.utils.ConstantPropertiesUtils;
import com.zero.yygh.vo.msm.MsmVo;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * @author zero
 * @desc
 * @create 2021/4/2
 */
@Service
public class MsmServiceImpl implements MsmService {
    /**
     * 发送手机验证码
     * @param phone 手机号
     * @param code  验证码
     * @return boolean
     * @author zero
     * @date 2021/4/2 15:49
     */
    @Override
    public boolean send (String phone, String code) {
        if (StringUtils.isEmpty(phone)) {
            return false;
        }
        // 整合阿里云短信相关
        DefaultProfile profile = DefaultProfile.getProfile(ConstantPropertiesUtils.REGION_ID,
                ConstantPropertiesUtils.ACCESS_KEY_ID,
                ConstantPropertiesUtils.SECRET);
        IAcsClient iAcsClient = new DefaultAcsClient(profile);
        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");

        //手机号
        request.putQueryParameter("PhoneNumbers", phone);
        //签名名称
        request.putQueryParameter("SignName", "我的谷粒在线教育网站");
        //模板code
        request.putQueryParameter("TemplateCode", "SMS_180051135");
        //验证码  使用json格式   {"code":"123456"}
        Map<String,Object> param = new HashMap<>(1);
        param.put("code",code);
        request.putQueryParameter("TemplateParam", JSONObject.toJSONString(param));

        //调用方法进行短信发送
        try {
            CommonResponse response = iAcsClient.getCommonResponse(request);
            System.out.println(response.getData());
            return response.getHttpResponse().isSuccess();
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return false;

    }

    /**
     * 发送下单成功短信
     * @param msmVo 下单短信内容
     * @return boolean
     * @author zero
     * @date 2021/5/10 10:17
     */
    @Override
    public boolean send (MsmVo msmVo) {
        if(!StringUtils.isEmpty(msmVo.getPhone())){
            String code = (String) msmVo.getParam().get("code");
            return this.send(msmVo.getPhone(), code);
        }
        return false;
    }
}
